#include "db_client.h"
#include "service.h"
#include "db_connection.h"
#include "db_proto.h"
#include "jmsg.h"
#include "db_client_handler.h"
DBClient::DBClient( Service* service, std::string host, int port )
{
	m_proto = db_protoCreateProto();
	m_service = service;
	m_dbconn = new DBConnection(service, host, port);
	m_dbconn->setHandler(this);
	
}

void DBClient::validatePlayerLogin( const std::string& playerId, const string& password, bool isGuest )
{
	DBMsgPlayerInfoRequest msg;
	msg.userName = playerId;
	msg.password = password;
	msg.isGuest = isGuest;

	JMsgWriter writer;
	msg.encode(m_proto, &writer);
	m_dbconn->sendData(writer.getBuffer(), writer.getBufferLen());
}

void DBClient::onDBConnectionData( void* data, int len )
{
	bool isSuccess = true;
	JMsgReader reader((unsigned char*)data, len);
	int typeId = reader.peekMessageTypeId(isSuccess);

	if (typeId == kDBMsgPlayerInfoResponse) {
		DBMsgPlayerInfoResponse resp;
		resp.decode(m_proto, &reader);

		if (m_handler) {
			m_handler->onDBPlayerInfoResponse(&resp);
		}
	}
	else if (typeId == kDBMsgAddRegisterPlayerResponse) {
		DBMsgAddRegisterPlayerResponse resp;
		resp.decode(m_proto, &reader);

		if (m_handler) {
			m_handler->onDBMsgAddRegisterPlayerResponse(&resp);
		}
	}
	else if (typeId == kDBMsgActivatePlayerResponse) {
		DBMsgActivatePlayerResponse resp;
		resp.decode(m_proto, &reader);

		if (m_handler) {
			m_handler->onDBMsgActivatePlayerResponse(&resp);
		}
	}
}

void DBClient::setHandler( DBClientHandler* handler )
{
	m_handler = handler;
}

